package orbito.util;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class Sieve<T> {
	LinkedList<T> list;
	int count;
	Comparator<T> cmp;
	
	public Sieve(int count, Comparator<T> cmp) {
		this.list = new LinkedList<T>();
		this.count = count;
		this.cmp = cmp;
	}
	
	public void add(T object) {
		if (list.size() < count) {
			list.add(object);
			Collections.sort(list, cmp);
		} else {
			if (cmp.compare(object, list.getLast()) < 0) {
				list.removeLast();
				list.add(object);
				Collections.sort(list, cmp);
			}
		}
	}
	
	public List<T> getItems() {
		return list;
	}
	
	public static void main(String[] args) {
		Sieve<Double> sieve = new Sieve<Double>(1, new Comparator<Double>() {
			public int compare(Double a, Double b) {
				return a.compareTo(b);
			}
		});
		
		Random rand = new Random(1);
		double[] numbers = new double[7];
		
		System.out.println("Numbers are:");
		for (int i = 0; i < numbers.length; i++) {
			numbers[i] = rand.nextDouble();
			sieve.add(numbers[i]);
			System.out.printf("%.2f\n", numbers[i]);
		}
		
		System.out.println("Sifted numbers are:");
		for (Double d : sieve.getItems()) {
			System.out.printf("%.2f\n", d);
		}
	}
}
